package test.html;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import docks.Dock;
import docks.DockAPI;
import docks.DockAPIImpl;

public class GetHTML {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public static void main(String[] args) throws JDOMException, IOException {
		// TODO Auto-generated method stub
		
		
		DockAPI api = new DockAPIImpl("http://www.bicing.cat/localizaciones/localizaciones.php?TU5fTE9DQUxJWkFDSU9ORVM%3D&MQ%3D%3D","bycicles.xml");
		
		api.getDockInfo(null);
		
//		List<Dock> docks = api.getAllDocks();
//		
//		for (Dock d : docks) {
//			
//			System.out.println(d.longitude + " " + d.latitude);
//		}
		
		
//		System.out.println("Fetching connection...");
//		String html = getHTML("http://www.bicing.cat/localizaciones/localizaciones.php?TU5fTE9DQUxJWkFDSU9ORVM%3D&MQ%3D%3D");
//		//System.out.println(html);
//		parseXML(html);
	}
	
	 private static void parseXML(String html) throws JDOMException, IOException {
		
		int beginIndex = html.indexOf("<Document>");
		int endIndex = html.indexOf("</Document>");
		html = html.substring(beginIndex, endIndex + "</Document>".length());
		Writer w = new OutputStreamWriter(new FileOutputStream("bycicles.xml"), "UTF-8");  
		w.write(html);
		w.close();
//		FileWriter fw = new FileWriter("bycicles.xml");
//		fw.write(html);
//		fw.close();
//		System.out.println(html);
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build("bycicles.xml");
		Element root = doc.getRootElement();
		List<Element> bycicles = root.getChildren("Placemark");
		for (Element i : bycicles) {
			
			Element j = i.getChild("Point");
			j = j.getChild("coordinates");
			System.out.println(j.getText());		
		}
		
	}

	public static String getHTML(String urlToRead) {
	      URL url; // The URL to read
	      HttpURLConnection conn; // The actual connection to the web page
	      BufferedReader rd; // Used to read results from the web page
	      String line; // An individual line of the web page HTML
	      String result = ""; // A long string containing all the HTML
	      try {
	         url = new URL(urlToRead);
	         conn = (HttpURLConnection) url.openConnection();
	         conn.setRequestMethod("GET");
	         rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	         while ((line = rd.readLine()) != null) {
	            result += line;
	            result +="\n";
	         }
	         rd.close();
	      } catch (Exception e) {
	         e.printStackTrace();
	      }
	      return result;
	   }

}
